import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from docx import Document
from docx.shared import Pt, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.section import WD_ORIENT
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
from datetime import datetime
import re

class OfficialDocumentGenerator:
    def __init__(self):
        # 页面设置 (单位: 厘米)
        self.top_margin = 3.7
        self.bottom_margin = 3.5
        self.left_margin = 2.8
        self.right_margin = 2.6

        # 字体设置
        self.title_font = "小标宋体"
        self.body_font = "仿宋_GB2312"
        self.sender_font = "仿宋_GB2312"
        self.black_font = "黑体"
        self.kai_font = "楷体_GB2312"

    def set_margins(self, doc):
        """设置页面边距"""
        section = doc.sections[0]
        section.top_margin = Inches(self.top_margin / 2.54)
        section.bottom_margin = Inches(self.bottom_margin / 2.54)
        section.left_margin = Inches(self.left_margin / 2.54)
        section.right_margin = Inches(self.right_margin / 2.54)

    def set_base_style(self, doc):
        """设置基础样式"""
        style = doc.styles['Normal']
        font = style.font
        font.name = self.body_font
        font.size = Pt(16)  # 三号字
        style.paragraph_format.line_spacing = Pt(29)  # 固定值29磅
        style.paragraph_format.space_before = Pt(0)
        style.paragraph_format.space_after = Pt(0)

        # 设置中文字体
        doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)

    def add_document_number(self, doc, number):
        """添加份号"""
        if number.strip():
            p = doc.add_paragraph()
            p.alignment = WD_ALIGN_PARAGRAPH.LEFT
            run = p.add_run(number)
            run.font.size = Pt(16)  # 三号
            run.font.name = 'Times New Roman'

    def add_secret_level(self, doc, level, period):
        """添加密级和保密期限"""
        if level.strip() and period.strip():
            p = doc.add_paragraph()
            p.alignment = WD_ALIGN_PARAGRAPH.LEFT
            run = p.add_run(f"{level}★{period}")
            run.font.size = Pt(16)
            run.font.name = self.black_font
            run.font.bold = True
            run._element.rPr.rFonts.set(qn('w:eastAsia'), self.black_font)

    def add_urgency_level(self, doc, level):
        """添加紧急程度"""
        if level.strip():
            p = doc.add_paragraph()
            p.alignment = WD_ALIGN_PARAGRAPH.LEFT
            run = p.add_run(level)
            run.font.size = Pt(16)
            run.font.name = self.black_font
            run.font.bold = True
            run._element.rPr.rFonts.set(qn('w:eastAsia'), self.black_font)

    def add_issuing_authority(self, doc, authority):
        """添加发文机关标志"""
        for _ in range(2):  # 空两行
            doc.add_paragraph()

        p = doc.add_paragraph()
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = p.add_run(authority)
        run.font.size = Pt(22)  # 小初号
        run.font.name = self.title_font
        run.font.bold = True
        run._element.rPr.rFonts.set(qn('w:eastAsia'), self.title_font)

    def add_document_code(self, doc, code, is_upward=False):
        """添加发文字号"""
        for _ in range(2):  # 空两行
            doc.add_paragraph()

        p = doc.add_paragraph()
        if is_upward:
            p.paragraph_format.left_indent = Pt(16)  # 上行文左空1字
        else:
            p.alignment = WD_ALIGN_PARAGRAPH.CENTER  # 平行文/下行文居中

        run = p.add_run(code)
        run.font.size = Pt(16)
        run.font.name = self.body_font
        run._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)

    def add_issuer(self, doc, issuer_name):
        """添加签发人"""
        p = doc.add_paragraph()
        p.paragraph_format.left_indent = Pt(16)  # 左空1字

        # "签发人"三字用仿宋
        run1 = p.add_run("签发人：")
        run1.font.size = Pt(16)
        run1.font.name = self.body_font
        run1._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)

        # 签发人姓名用楷体
        run2 = p.add_run(issuer_name)
        run2.font.size = Pt(16)
        run2.font.name = self.kai_font
        run2._element.rPr.rFonts.set(qn('w:eastAsia'), self.kai_font)

    def add_red_line(self, doc):
        """添加红色分隔线"""
        p = doc.add_paragraph()
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = p.add_run("_" * 28)  # 约版心宽度
        run.font.color.rgb = RGBColor(255, 0, 0)

    def add_title(self, doc, title):
        """添加公文标题"""
        for _ in range(2):  # 空两行
            doc.add_paragraph()

        p = doc.add_paragraph()
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = p.add_run(title)
        run.font.size = Pt(22)  # 二号
        run.font.name = self.title_font
        run.font.bold = True
        run._element.rPr.rFonts.set(qn('w:eastAsia'), self.title_font)

    def add_body_content(self, doc, content):
        """添加正文内容"""
        doc.add_paragraph()  # 空一行

        # 处理不同级别的标题
        lines = content.split('\n')
        for line in lines:
            if not line.strip():
                doc.add_paragraph()
                continue

            p = doc.add_paragraph()
            p.paragraph_format.line_spacing = Pt(29)

            # 判断标题级别
            if line.startswith("一、") or line.startswith("二、") or line.startswith("三、"):
                # 一级标题 (3号黑体)
                run = p.add_run(line)
                run.font.size = Pt(16)
                run.font.name = self.black_font
                run.font.bold = True
                run._element.rPr.rFonts.set(qn('w:eastAsia'), self.black_font)
            elif line.startswith("（一）") or line.startswith("（二）"):
                # 二级标题 (3号楷体)
                run = p.add_run(line)
                run.font.size = Pt(16)
                run.font.name = self.kai_font
                run._element.rPr.rFonts.set(qn('w:eastAsia'), self.kai_font)
            elif re.match(r'^\d+\.', line):
                # 三级标题 (3号仿宋)
                run = p.add_run(line)
                run.font.size = Pt(16)
                run.font.name = self.body_font
                run._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)
            elif re.match(r'^（\d+）', line):
                # 四级标题 (3号仿宋)
                run = p.add_run(line)
                run.font.size = Pt(16)
                run.font.name = self.body_font
                run._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)
            else:
                # 普通正文 (3号仿宋)
                run = p.add_run(line)
                run.font.size = Pt(16)
                run.font.name = self.body_font
                run._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)

    def add_attachments(self, doc, attachments):
        """添加附件说明"""
        if not attachments.strip():
            return

        doc.add_paragraph()  # 空一行

        p = doc.add_paragraph()
        p.paragraph_format.left_indent = Pt(32)  # 左空2字 (1字=16磅)

        # 处理多个附件
        attach_list = [a.strip() for a in attachments.split('\n') if a.strip()]
        if len(attach_list) == 1:
            run = p.add_run("附件：" + attach_list[0])
        else:
            run = p.add_run("附件：\n")
            for i, attach in enumerate(attach_list, 1):
                run = p.add_run(f"{i}. {attach}\n")

        run.font.size = Pt(16)
        run.font.name = self.body_font
        run._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)

    def add_issuing_info(self, doc, authority, date):
        """添加发文机关署名和成文日期"""
        for _ in range(3):  # 空三行
            doc.add_paragraph()

        # 发文机关
        p = doc.add_paragraph()
        p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
        p.paragraph_format.right_indent = Pt(64)  # 右空4字
        run = p.add_run(authority)
        run.font.size = Pt(16)
        run.font.name = self.sender_font
        run._element.rPr.rFonts.set(qn('w:eastAsia'), self.sender_font)

        # 成文日期
        p = doc.add_paragraph()
        p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
        p.paragraph_format.right_indent = Pt(64)  # 右空4字
        run = p.add_run(date)
        run.font.size = Pt(16)
        run.font.name = self.sender_font
        run._element.rPr.rFonts.set(qn('w:eastAsia'), self.sender_font)

    def add_contact_info(self, doc, contact, phone):
        """添加附注(联系人信息)"""
        if not contact.strip() and not phone.strip():
            return

        info = []
        if contact.strip():
            info.append(f"联系人：{contact}")
        if phone.strip():
            info.append(f"电话：{phone}")

        p = doc.add_paragraph()
        p.paragraph_format.left_indent = Pt(32)  # 左空2字
        run = p.add_run(f"（{' '.join(info)}）")
        run.font.size = Pt(16)
        run.font.name = self.body_font
        run._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)

    def add_copy_to(self, doc, copy_to):
        """添加抄送机关"""
        if not copy_to.strip():
            return

        # 添加分隔线
        p = doc.add_paragraph()
        run = p.add_run("_" * 28)  # 约版心宽度
        run.font.size = Pt(12)

        # 抄送机关
        p = doc.add_paragraph()
        p.paragraph_format.left_indent = Pt(16)  # 左空1字
        run = p.add_run("抄送：" + copy_to + "。")  # 最后机关加句号
        run.font.size = Pt(14)  # 4号字
        run.font.name = self.body_font
        run._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)

    def add_print_info(self, doc, print_office, print_date):
        """添加印发机关和日期"""
        p = doc.add_paragraph()

        # 印发机关 (左空1字)
        run1 = p.add_run(print_office)
        run1.font.size = Pt(14)  # 4号
        run1.font.name = self.body_font
        run1._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)

        # 印发日期 (右空1字)
        run2 = p.add_run("\t" + print_date)  # 使用制表符右对齐
        run2.font.size = Pt(14)  # 4号
        run2.font.name = self.body_font
        run2._element.rPr.rFonts.set(qn('w:eastAsia'), self.body_font)

    def add_page_numbers(self, doc):
        def create_page_number_field(paragraph):
            """创建页码字段（PAGE）"""
            # 清除段落内容
            #paragraph.clear()

            # 创建字段运行
            run = paragraph.add_run()

            # 开始字段
            fld_char1 = OxmlElement('w:fldChar')
            fld_char1.set(qn('w:fldCharType'), 'begin')
            run._r.append(fld_char1)

            # 指令文本
            instr_text = OxmlElement('w:instrText')
            instr_text.set(qn('xml:space'), 'preserve')
            instr_text.text = "PAGE"
            run._r.append(instr_text)

            # 结束字段
            fld_char2 = OxmlElement('w:fldChar')
            fld_char2.set(qn('w:fldCharType'), 'end')
            run._r.append(fld_char2)

            return run

        def create_symmetric_page_number(paragraph, is_odd_page=True):
            """创建对称页码格式
            奇数页：右对齐，"— [页码] —\u2002"
            偶数页：左对齐，"\u2002— [页码] —"
            """
            paragraph.clear()

            # 设置段落格式
            for run in paragraph.runs:
                run.font.name = "Times New Roman"
                run._element.rPr.rFonts.set(qn('w:eastAsia'), "宋体")
                run.font.size = Pt(12)

            # 根据奇偶页添加不同内容
            if is_odd_page:
                # 奇数页：— [页码] —\u2002
                paragraph.add_run("— ").font.name = "Times New Roman"
                page_run = create_page_number_field(paragraph)
                paragraph.add_run(" —\u2002").font.name = "Times New Roman"
                paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
            else:
                # 偶数页：\u2002— [页码] —
                paragraph.add_run("\u2002— ").font.name = "Times New Roman"
                page_run = create_page_number_field(paragraph)
                paragraph.add_run(" —").font.name = "Times New Roman"
                paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT

            # 统一所有运行的字体格式
            for run in paragraph.runs:
                run.font.name = "Times New Roman"
                run._element.rPr.rFonts.set(qn('w:eastAsia'), "宋体")
                run.font.size = Pt(12)

        # 启用奇偶页不同
        doc.settings.element.append(OxmlElement('w:evenAndOddHeaders'))

        # 处理每一节
        for section in doc.sections:
            section.footer_distance = Inches(0.28)  # 页脚距离

            # 处理奇数页页脚
            odd_page_footer = section.footer
            odd_page_footer.is_linked_to_previous = False
            if odd_page_footer.paragraphs:
                create_symmetric_page_number(odd_page_footer.paragraphs[0], is_odd_page=True)

            # 处理偶数页页脚
            even_page_footer = section.even_page_footer
            even_page_footer.is_linked_to_previous = False
            if even_page_footer.paragraphs:
                create_symmetric_page_number(even_page_footer.paragraphs[0], is_odd_page=False)

        print("注意：生成文档后，请在Word中按F9更新所有字段以显示正确页码。")

    def create_document(self, params):
        """创建公文文档"""
        doc = Document()

        # 设置基本样式
        self.set_margins(doc)
        self.set_base_style(doc)

        # 1. 添加版头部分
        self.add_document_number(doc, params.get('document_number', ''))
        self.add_secret_level(doc, params.get('secret_level', ''), params.get('secret_period', ''))
        self.add_urgency_level(doc, params.get('urgency_level', ''))
        self.add_issuing_authority(doc, params['issuing_authority'])

        # 发文字号和签发人
        is_upward = params.get('is_upward', False)
        self.add_document_code(doc, params['document_code'], is_upward)
        if is_upward and params.get('issuer_name'):
            self.add_issuer(doc, params['issuer_name'])

        # 2. 添加主体部分
        self.add_red_line(doc)
        self.add_title(doc, params['title'])
        self.add_body_content(doc, params['content'])
        self.add_attachments(doc, params.get('attachments', ''))
        self.add_issuing_info(doc, params['issuing_authority'], params['issue_date'])
        self.add_contact_info(doc, params.get('contact', ''), params.get('phone', ''))

        # 3. 添加版记部分
        self.add_copy_to(doc, params.get('copy_to', ''))
        self.add_print_info(doc, params.get('print_office', ''), params.get('print_date', ''))

        # 保存文档前添加页码
        self.add_page_numbers(doc)

        # 保存文档
        doc.save(params['output_path'])

class OfficialDocApp:
    def __init__(self, root):
        self.root = root
        root.title("党政机关公文生成系统 v0.5")
        #root.geometry("900x700")
        # 设置窗口尺寸和居中
        self.window_width = 900
        self.window_height = 700
        self.center_window(root, self.window_width, self.window_height)

        # 禁止调整窗口大小（可选）
        root.resizable(False, False)

        # 初始化生成器
        self.generator = OfficialDocumentGenerator()

        # 创建主框架
        self.main_frame = ttk.Frame(root)
        self.main_frame.pack(fill='both', expand=True, padx=10, pady=10)

        # 创建Notebook分页
        self.notebook = ttk.Notebook(self.main_frame)
        self.notebook.pack(fill='both', expand=True)

        # 创建标签页
        self.create_header_tab()
        self.create_body_tab()
        self.create_footer_tab()

        # 创建底部按钮
        self.create_buttons()

    def center_window1(self, window, width, height):
        """窗口居中显示"""
        screen_width = window.winfo_screenwidth()
        screen_height = window.winfo_screenheight()

        x = (screen_width - width) // 2
        y = (screen_height - height) // 2

        window.geometry(f"{width}x{height}+{x}+{y}")

    def center_window(self, window, width, height):
        """精确居中（考虑任务栏和窗口装饰）"""
        # 更新窗口几何信息（确保获取到实际尺寸）
        window.update_idletasks()
        
        # 计算窗口装饰的额外宽度/高度
        frame_width = window.winfo_rootx() - window.winfo_x()
        titlebar_height = window.winfo_rooty() - window.winfo_y()
        adjust_width = width + 2 * frame_width
        adjust_height = height + titlebar_height + frame_width
        
        # 获取可用屏幕区域（排除任务栏）
        screen_width = window.winfo_screenwidth()
        screen_height = window.winfo_screenheight()
        
        # 计算精确位置
        x = max(0, (screen_width - adjust_width) // 2)
        y = max(0, (screen_height - adjust_height) // 2 - titlebar_height // 2)
        
        window.geometry(f"{width}x{height}+{x}+{y}")

    def create_header_tab(self):
        """创建版头信息标签页"""
        tab = ttk.Frame(self.notebook)
        self.notebook.add(tab, text="版头信息")

        # 使用网格布局
        for i in range(8):  # 创建8行
            tab.grid_rowconfigure(i, weight=1)
        for j in range(4):  # 创建4列
            tab.grid_columnconfigure(j, weight=1)

        # 份号
        ttk.Label(tab, text="份号(可选):").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        self.document_number = ttk.Entry(tab, width=15)
        self.document_number.grid(row=0, column=1, padx=5, pady=5, sticky="w")
        ttk.Label(tab, text="6位阿拉伯数字，如'000001'").grid(row=0, column=2, padx=5, sticky="w")

        # 密级和保密期限
        ttk.Label(tab, text="密级(可选):").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        self.secret_level = ttk.Combobox(tab, values=["", "绝密", "机密", "秘密"], width=8)
        self.secret_level.grid(row=1, column=1, padx=5, pady=5, sticky="w")

        ttk.Label(tab, text="保密期限:").grid(row=1, column=2, padx=5, pady=5, sticky="e")
        self.secret_period = ttk.Entry(tab, width=8)
        self.secret_period.grid(row=1, column=3, padx=5, pady=5, sticky="w")
        ttk.Label(tab, text="如'1年'、'10年'").grid(row=1, column=4, padx=5, sticky="w")

        # 紧急程度
        ttk.Label(tab, text="紧急程度(可选):").grid(row=2, column=0, padx=5, pady=5, sticky="e")
        self.urgency_level = ttk.Combobox(tab, values=["", "特急", "加急", "平急"], width=8)
        self.urgency_level.grid(row=2, column=1, padx=5, pady=5, sticky="w")

        # 发文机关标志
        ttk.Label(tab, text="发文机关标志:").grid(row=3, column=0, padx=5, pady=5, sticky="e")
        self.issuing_authority = ttk.Entry(tab, width=40)
        self.issuing_authority.grid(row=3, column=1, columnspan=3, padx=5, pady=5, sticky="we")
        self.issuing_authority.insert(0, "XX市XX局文件")

        # 发文字号
        ttk.Label(tab, text="发文字号:").grid(row=4, column=0, padx=5, pady=5, sticky="e")
        self.document_code = ttk.Entry(tab, width=25)
        self.document_code.grid(row=4, column=1, padx=5, pady=5, sticky="w")
        self.document_code.insert(0, "XX发〔2023〕1号")

        # 行文方向
        ttk.Label(tab, text="行文方向:").grid(row=5, column=0, padx=5, pady=5, sticky="e")
        self.doc_direction = ttk.Combobox(tab, values=["下行文/平行文", "上行文"], width=15)
        self.doc_direction.grid(row=5, column=1, padx=5, pady=5, sticky="w")
        self.doc_direction.current(0)
        self.doc_direction.bind("<<ComboboxSelected>>", self.toggle_issuer_field)

        # 签发人 (初始隐藏)
        self.issuer_label = ttk.Label(tab, text="签发人:")
        self.issuer_entry = ttk.Entry(tab, width=10)

        # 公文标题
        ttk.Label(tab, text="公文标题:").grid(row=6, column=0, padx=5, pady=5, sticky="e")
        self.title = ttk.Entry(tab, width=40)
        self.title.grid(row=6, column=1, columnspan=3, padx=5, pady=5, sticky="we")
        self.title.insert(0, "关于XXXX工作的报告")

    def toggle_issuer_field(self, event=None):
        """切换签发人字段显示"""
        if self.doc_direction.get() == "上行文":
            self.issuer_label.grid(row=5, column=2, padx=5, pady=5, sticky="e")
            self.issuer_entry.grid(row=5, column=3, padx=5, pady=5, sticky="w")
        else:
            self.issuer_label.grid_forget()
            self.issuer_entry.grid_forget()

    def create_body_tab(self):
        """创建正文标签页"""
        tab = ttk.Frame(self.notebook)
        self.notebook.add(tab, text="正文内容")

        # 正文编辑区
        self.content_text = tk.Text(tab, wrap='word', font=('仿宋_GB2312', 12))
        self.content_text.pack(fill='both', expand=True, padx=5, pady=5)

        # 添加示例内容
        example_content = """区政府：

根据《党政机关公文格式》（GB/T 9704-2012）要求，现就有关事项报告如下：

一、基本情况
（一）项目背景
1. 项目概况
（1）项目名称：XXX项目

二、存在问题

三、工作建议

请批示。"""
        self.content_text.insert('1.0', example_content)

        # 添加工具栏
        toolbar = ttk.Frame(tab)
        toolbar.pack(fill='x', padx=5, pady=5)

        ttk.Button(toolbar, text="一级标题", command=lambda: self.insert_title("一、")).pack(side='left', padx=2)
        ttk.Button(toolbar, text="二级标题", command=lambda: self.insert_title("（一）")).pack(side='left', padx=2)
        ttk.Button(toolbar, text="三级标题", command=lambda: self.insert_title("1.")).pack(side='left', padx=2)
        ttk.Button(toolbar, text="四级标题", command=lambda: self.insert_title("（1）")).pack(side='left', padx=2)

    def insert_title(self, prefix):
        """插入标题"""
        current_pos = self.content_text.index(tk.INSERT)
        self.content_text.insert(current_pos, prefix)

    def create_footer_tab(self):
        """创建版记标签页"""
        tab = ttk.Frame(self.notebook)
        self.notebook.add(tab, text="版记信息")

        # 使用网格布局
        for i in range(8):  # 创建8行
            tab.grid_rowconfigure(i, weight=1)
        for j in range(4):  # 创建4列
            tab.grid_columnconfigure(j, weight=1)

        # 附件说明
        ttk.Label(tab, text="附件说明(可选):").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        self.attachments = tk.Text(tab, height=3, width=30, font=('仿宋_GB2312', 10))
        self.attachments.grid(row=0, column=1, columnspan=3, padx=5, pady=5, sticky="we")
        self.attachments.insert('1.0', "1. 实施方案.docx\n2. 预算表.xlsx")

        # 发文机关署名 (与版头相同)

        # 成文日期
        ttk.Label(tab, text="成文日期:").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        self.issue_date = ttk.Entry(tab, width=15)
        self.issue_date.grid(row=1, column=1, padx=5, pady=5, sticky="w")
        self.issue_date.insert(0, datetime.now().strftime("%Y年%m月%d日"))

        # 联系人信息
        ttk.Label(tab, text="联系人(可选):").grid(row=2, column=0, padx=5, pady=5, sticky="e")
        self.contact = ttk.Entry(tab, width=15)
        self.contact.grid(row=2, column=1, padx=5, pady=5, sticky="w")

        ttk.Label(tab, text="电话(可选):").grid(row=2, column=2, padx=5, pady=5, sticky="e")
        self.phone = ttk.Entry(tab, width=15)
        self.phone.grid(row=2, column=3, padx=5, pady=5, sticky="w")

        # 抄送机关
        ttk.Label(tab, text="抄送机关(可选):").grid(row=3, column=0, padx=5, pady=5, sticky="e")
        self.copy_to = tk.Text(tab, height=3, width=30, font=('仿宋_GB2312', 10))
        self.copy_to.grid(row=3, column=1, columnspan=3, padx=5, pady=5, sticky="we")
        self.copy_to.insert('1.0', "XX局, XX办公室, XX处")

        # 印发机关
        ttk.Label(tab, text="印发机关:").grid(row=4, column=0, padx=5, pady=5, sticky="e")
        self.print_office = ttk.Entry(tab, width=25)
        self.print_office.grid(row=4, column=1, padx=5, pady=5, sticky="w")
        self.print_office.insert(0, "XX局办公室")

        # 印发日期
        ttk.Label(tab, text="印发日期:").grid(row=4, column=2, padx=5, pady=5, sticky="e")
        self.print_date = ttk.Entry(tab, width=15)
        self.print_date.grid(row=4, column=3, padx=5, pady=5, sticky="w")
        self.print_date.insert(0, datetime.now().strftime("%Y年%m月%d日"))

    def create_buttons(self):
        """创建底部按钮"""
        button_frame = ttk.Frame(self.main_frame)
        button_frame.pack(fill='x', padx=5, pady=5)

        ttk.Button(button_frame, text="生成公文", command=self.generate_document).pack(side='right', padx=5)
        ttk.Button(button_frame, text="退出", command=self.root.quit).pack(side='right', padx=5)

    def generate_document(self):
        """生成公文文档"""
        # 收集所有参数
        params = {
            'document_number': self.document_number.get(),
            'secret_level': self.secret_level.get(),
            'secret_period': self.secret_period.get(),
            'urgency_level': self.urgency_level.get(),
            'issuing_authority': self.issuing_authority.get(),
            'document_code': self.document_code.get(),
            'is_upward': (self.doc_direction.get() == "上行文"),
            'issuer_name': self.issuer_entry.get() if self.doc_direction.get() == "上行文" else "",
            'title': self.title.get(),
            'content': self.content_text.get("1.0", tk.END),
            'attachments': self.attachments.get("1.0", tk.END),
            'issue_date': self.issue_date.get(),
            'contact': self.contact.get(),
            'phone': self.phone.get(),
            'copy_to': self.copy_to.get("1.0", tk.END),
            'print_office': self.print_office.get(),
            'print_date': self.print_date.get(),
        }

        # 验证必填字段
        if not params['issuing_authority']:
            messagebox.showerror("错误", "必须填写发文机关标志！")
            return
        if not params['document_code']:
            messagebox.showerror("错误", "必须填写发文字号！")
            return
        if not params['title']:
            messagebox.showerror("错误", "必须填写公文标题！")
            return
        if not params['content'].strip():
            messagebox.showerror("错误", "公文正文不能为空！")
            return

        # 选择保存路径
        output_path = filedialog.asksaveasfilename(
            defaultextension=".docx",
            filetypes=[("Word文档", "*.docx")],
            title="保存公文"
        )
        if not output_path:
            return  # 用户取消保存

        params['output_path'] = output_path

        try:
            self.generator.create_document(params)
            messagebox.showinfo("成功", f"公文已成功生成！\n保存路径: {output_path}")
        except Exception as e:
            messagebox.showerror("错误", f"生成公文时出错:\n{str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = OfficialDocApp(root)
    root.mainloop()